import React, { useEffect, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import { alpha, Box } from "@mui/material";
//import { getHandleLawData, getUnhandleLawData } from "../../lib/getLaws";
import {
  getHandleLegalStorage,
  getUnHandleLegalStorage,
} from "../../localCache/legalContentStorage";
import AdaptiveTitle from "./AdaptiveTitle";
import ContentMain from "./ContentMain";
import NestedList from "./NestedList";
import Loading from "../../components/loading/Loading";

/**
 * 法律文本展示组件
 * @returns
 */
export default function ContentPresentation() {
  const [lawData, setLawData] = useState({});
  const [loading, setLoading] = useState(true);
  const anchors = useRef([]); // 未处理数据，用于锚点定位
  const refs = useRef({});
  const { id } = useParams(); //获取路由参数
  
  useEffect(() => {
    const getData = async () => {
      const handleData = await getHandleLegalStorage(id);
      const unhandleData = await getUnHandleLegalStorage(id);
      setLawData(handleData);
      anchors.current = Array.isArray(unhandleData) && [...unhandleData];
      anchors.current.forEach((item) => {
        refs.current[item._id] = refs.current[item.id] || React.createRef();
      });
      setLoading(false);
    };
    getData();
  }, [anchors]);

  if (loading) {
    return <Loading />;
  }

  return (
    <Box
      className="Container"
      sx={{ display: "flex", width: "100vw", height: "93.5vh" }}>
      {/* Sidebar */}
      <Box
        className="sidebarContainer"
        sx={{
          width: "18vw",
          maxWidth: "400px",
          minWidth: "200px",
          overflowY: "scroll",
          "&::-webkit-scrollbar": {
            display: "none",
            width: 12,
          },
          "&::-webkit-scrollbar-track": {
            background: (theme) => theme.palette.scrollTrackColor.main,
            borderRadius: 10,
          },
          "&::-webkit-scrollbar-thumb": {
            background: (theme) => theme.palette.scrollThumbColor.main,
            borderRadius: 10,
          },
          overflowX: "hidden",
          borderRight: "1px solid",
          borderColor: alpha("#e5e5e5", 0.15),
        }}>
        {lawData && <NestedList data={lawData} refs={refs.current} />}
      </Box>
      {/* main content */}
      <Box
        className="mainContentContainer"
        sx={{
          flex: 1,
          paddingLeft: "4.5rem",
          paddingRight: "4rem",
          paddingTop: "2rem",
          overflowY: "scroll",
          overflowX: "hidden",
        }}>
        <AdaptiveTitle item={lawData} />
        {lawData && <ContentMain data={lawData} refs={refs.current} />}
      </Box>
    </Box>
  );
}
